import math
import numpy as np
from nonlinear import NonLinear

def test_nonlinear():
    def f(x):
        return (pow(x, 2) + 2 - math.exp(x))/3
    def f1(x):
        return pow(x, 2) - 3*x + 2 - math.exp(x)

    def g(x):
        return 20/(pow(x, 2) + 2*x + 10)

    def g1(x):
        return pow(x, 3) + 2*pow(x, 2) + 10*x - 20

    non_linear = NonLinear([f])
    x0 = 0.00  # 设置初始值
    delta = 1e-8
    # 不动点迭代法
    x, count = non_linear.fixed_iter(x0, delta)
    print("------------------不动点迭代法-------------------")
    print(f"初始值: {x0}, 求得的根为: {x} 迭代次数为: {count}")
    
    # 斯蒂芬森加速迭代法
    x, count = non_linear.stefenson_iter(x0, delta)
    print("------------------斯蒂芬森迭代法------------------")
    print(f"初始值: {x0}, 求得的根为: {x}, 迭代次数为: {count}")
    
    # 牛顿迭代法
    non_linear = NonLinear([f1])
    x, count = non_linear.newton_iter(x0, delta)
    print("------------------牛顿迭代法----------------------")
    print(f"初始值: {x0}, 求得的根为: {x}, 迭代次数为: {count}")

    non_linear = NonLinear([g])
    x0 = 1.00  # 设置初始值
    delta = 1e-8
    # 不动点迭代法
    x, count = non_linear.fixed_iter(x0, delta)
    print("------------------不动点迭代法-------------------")
    print(f"初始值: {x0}, 求得的根为: {x} 迭代次数为: {count}")
    
    # 斯蒂芬森加速迭代法
    x, count = non_linear.stefenson_iter(x0, delta)
    print("------------------斯蒂芬森迭代法------------------")
    print(f"初始值: {x0}, 求得的根为: {x}, 迭代次数为: {count}")
    
    # 牛顿迭代法
    non_linear = NonLinear([g1])
    x, count = non_linear.newton_iter(x0, delta)
    print("------------------牛顿迭代法----------------------")
    print(f"初始值: {x0}, 求得的根为: {x}, 迭代次数为: {count}")

if __name__ == "__main__":
    test_nonlinear()